<template>
  <div v-if="isLoading">
    <p>加载中...</p> <!-- 加载消息或加载动画 -->
  </div>
  <div v-else>
    <div class="store" v-if="hasStore">
      <h2>我的商店</h2>
      <p class="intro">
        精选优质商品，提供卓越的购物体验。您可以管理您的商品。
      </p>
   
  
      <div class="product-list">
        <div v-for="product in products" :key="product.id" class="product-card">
          <img :src="product.image" alt="商品图片" class="product-image" />
          <h4>{{ product.name }}</h4>
          <p class="description">{{ product.description }}</p>
          <p class="price">价格: ￥{{ product.price }}</p>
          <div class="status-container">
            <p class="status">状态: {{ product.status === 1 ? '上架' : '下架' }}</p>
            
            <p class="stock">库存: {{ product.stock }}</p>
          </div>
          <div class="button-group">
            <el-button @click="toggleStatus(product)" type="success">
              {{ product.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button @click="showEditProductDialog(product)" type="info">修改</el-button>
          </div>
        </div>
        <div class="add-product-card" @click="showAddProductDialog">
          <el-button type="primary" class="add-button">+</el-button>
          <p>添加商品</p>
        </div>
      </div>
  
      <el-dialog :title="title" v-model="isDialogVisible" width="600px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" type="number" placeholder="请输入商品价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="category">
              <!-- <el-input v-model="form.category" placeholder="请输入商品类别" /> -->
              <el-select v-model="form.category" placeholder="选择商品类别"  style="margin-bottom: 20px;">
        <el-option v-for="category in categories" :key="category.id" :label="category.type" :value="category.id" />
      </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="选择商品状态">
                <el-option label="可供购买" value=1 />
                <el-option label="不可供购买" value=2 />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣价格" prop="discountPrice">
              <el-input v-model="form.discountPrice" type="number" placeholder="请输入折扣价格" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="销量" prop="salesVolume">
              <el-input v-model="form.salesVolume" type="number" placeholder="请输入销量" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input v-model="form.stock" type="number" placeholder="请输入库存数量" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" v-model="form.description" placeholder="请输入商品描述" />
            </el-form-item>
          </el-col>
          <!-- 商品图片 -->
          <el-col :span="24">
            <el-form-item label="商品图片" prop="image">
              <el-upload class="avatar-uploader" :show-file-list="false" max-size="4" :before-upload="beforeUpload" @success="handleSuccess" @error="handleError">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <div v-if="form.image" class="uploaded-image">
                <img :src="form.image" alt="上传的图片" style="max-width: 100%; margin-top: 10px;" />
              </div>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </div>
    <div v-else>
      <h2>您还没有商店，快去创建吧！</h2>
      <el-button type="primary"  @click="navigateToCreateStore">创建商店</el-button>
    </div>
  </div>
  </template>
  
  <script setup>
  import { ref,reactive} from 'vue';
  import {hasStoreByUserId} from "@/api/virtualStore"
  import { uploadImage } from "@/api/upload";
  import {getGoodsListByToken} from "@/api/product"
  import {addProduct,changeProductStatus} from "@/api/product"
  import {listProductTypes} from "@/api/productType"; // 假设存在的 API
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'


const categories = ref([]);

const getCategories = () => {
  categories.value = [
  ];

  listProductTypes().then(res => {
    categories.value = res.data;
  });




};

const router = useRouter();
// 检查 token 的方法
const hasToken = () => {
  // 假设 token 存储在 localStorage 中
  return localStorage.getItem('token') !== null;
};
// 路由跳转方法
const navigateToCreateStore = () => {
  if (hasToken()) {
    router.push('/createStore');
  } else {
    // 提示用户没有 token
    ElMessage.error('请先登录');
  }
};


const isLoading = ref(true); // 加载状态

const beforeUpload = (file) => {
  uploadImage(file).then(data => {
    form.value.image = data; 
  });
  return true; 
};

const handleSuccess = (response) => {
  form.value.image = response; 
};

const handleError = (err) => {
  console.error("上传失败:", err);
};

const mystore = ref(null)
const title = ref("");
const form = ref({
  id: undefined,
  name: "",
  price: 0,
  category: "",
  status: 1,
  discountPrice: null,
  salesVolume: 0,
  stock: 0,
  description: "",
  image: ""
});
const rules = {
  name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  price: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
  category: [{ required: true, message: "商品类别不能为空", trigger: "blur" }],
};

  //判断是否有店铺
  const hasStore = ref(false)
  const hasStoreByUserIdResult = () => {
  isLoading.value = true; // 设置加载状态为 true
  hasStoreByUserId().then(res => {
    if (res.data.hasStore) {
      hasStore.value = true;
      mystore.value = res.data;
      getProducts();
    }
  }).finally(() => {
    // 睡眠一秒
    setTimeout(() => {
      isLoading.value = false; // 数据获取后延迟一秒再将加载状态设为 false
    }, 100);
  });
};


  
  const products = ref([
  ]);
  //获取店铺商品列表
  const getProducts = () => {
    getGoodsListByToken().then(res => {
      products.value = res.data
    })
  }
  
  const isDialogVisible = ref(false);
  const editingProduct = ref(null);
  
  function showAddProductDialog() {
    resetForm();
    isDialogVisible.value = true;
  }
  
  function showEditProductDialog(product) {
    editingProduct.value = product;
    form.value = { ...product };
    isDialogVisible.value = true;
  }
  
  function resetForm() {
    form.value = { name: '', description: '', price: null, stock: null, image: '' };
    editingProduct.value = null;
    isDialogVisible.value = false;
  }

  // 取消按钮
const cancel = () => {
  isDialogVisible.value = false;
 
};
  
  function submitForm() {
    const params = { ...form.value };
    addProduct(params).then(res => {
      if (res.code === 200) {
        getProducts();
        isDialogVisible.value = false;
        } else {
          alert(res.message);
        }
      })


    resetForm();
  }
  
  
function toggleStatus(product) {
  ElMessageBox.confirm(
        '确定要' + (product.status === 1 ? '下架' : '上架') + '该商品吗?',
        '确认框',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning', // 这里的类型可以根据需要更改
        }
    ).then(() => {
      changeProductStatus(product.id).then(res => {
        if (res.code === 200) {
          getProducts();
          ElMessage.success('操作成功');
        } else {
          ElMessage.error('操作失败');
        }
      })
    }).catch(() => {
      // 用户取消操作
    });
    
  }
  onMounted(() => {
    hasStoreByUserIdResult()
    getCategories();
  })
  </script>
  
  <style scoped>
  .store {
    width: 95vw; /* 全屏宽度 */
    height: 100vh; /* 全屏高度 */
    padding: 20px;
    background-color: #f8f9fa;
    overflow-y: auto; /* 允许纵向滚动 */
  }
  
  h2 {
    font-family: 'Georgia', serif;
    color: #4a4a4a;
    font-size: 2.5em;
    margin-bottom: 10px;
    text-align: center; /* 居中对齐 */
  }
  
  .intro {
    font-size: 1.2em;
    color: #777;
    text-align: center; /* 居中对齐 */
    margin-bottom: 30px;
  }
  
  .product-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* 自适应网格布局 */
    gap: 20px; /* 卡片间距 */
    padding: 0; /* 消除内边距 */
    margin-top: 20px; /* 上方间距 */
  }
  
  .product-card {
    border: 1px solid #ddd;
    border-radius: 10px;
    background-color: #fff;
    padding: 20px;
    transition: transform 0.3s, box-shadow 0.3s;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center; /* 居中对齐 */
    font-size: 15px;
    break-inside: avoid; /* 防止在卡片内部断裂 */
    height: auto; /* 高度自适应 */
  }
  
  .product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  }
  
  .product-image {
    width: 100%; /* 图片宽度自适应 */
    height: auto; /* 高度自适应 */
    border-radius: 10px; /* 圆角 */
    margin-bottom: 10px; /* 图片与下方内容间距 */
  }
  
  .description {
    font-size: 0.9em;
    color: #555;
    margin: 10px 0;
  }
  
  .price {
    font-size: 1em;
    color: #e67e22; /* 使用橙色突出价格 */
    margin: 10px 0;
  }
  .dialog-footer{
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }
  
  .status-container {
    display: flex; /* 使用 Flexbox 布局 */
    justify-content: space-between; /* 均分一行 */
    margin-top: 10px; /* 与其他内容的间距 */
  }
  
  .status, .stock {
    margin: 0; /* 消除默认边距 */
  }
  
  .button-group {
    display: flex; /* 使用 Flexbox 布局 */
    justify-content: space-between; /* 均分一行 */
    margin-top: 10px; /* 按钮与其他内容的间距 */
  }
  
  .add-product-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed #ddd;
    border-radius: 10px;
    background-color: #f8f9fa;
    padding: 20px;
    cursor: pointer;
    text-align: center;
    transition: background-color 0.3s;
  }
  
  .add-product-card:hover {
    background-color: #e9ecef; /* 悬停效果 */
  }
  
  .add-button {
    font-size: 2em;
    width: 60px;
    height: 60px;
    border-radius: 50%; /* 圆形按钮 */
    padding: 0;
  }
  </style>